<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JavaScript 数组操作示例</title>
  </head>
  <body>
    <script>
      // 添加/删除元素
      let arr = ["A", "B", "C"];
      arr.push("D");
      console.log("\n--- 添加/删除元素 ---");
      console.log("push后:", arr);
      arr.pop();
      console.log("pop后:", arr);
      arr.unshift("X");
      console.log("unshift后:", arr);
      arr.shift();
      console.log("shift后:", arr);
      arr.splice(1, 0, "Y", "Z");
      console.log("splice添加后:", arr);
      arr.splice(2, 1);
      console.log("splice删除后:", arr);

      // 遍历数组
      let nums = [1, 2, 3, 4, 5];
      console.log("\n--- 遍历数组 ---");
      console.log("for循环:");
      for (let i = 0; i < nums.length; i++) {
        console.log(nums[i]);
      }
      console.log("forEach:");
      nums.forEach(function (num) {
        console.log(num * 2);
      });
      console.log("for...of:");
      for (let num of nums) {
        console.log(num);
      }

      // 查找元素
      let fruitList = ["苹果", "香蕉", "橙子", "葡萄"];
      console.log("\n--- 查找元素 ---");
      console.log("香蕉的索引:", fruitList.indexOf("香蕉"));
      console.log("西瓜的索引:", fruitList.indexOf("西瓜"));
      console.log("包含橙子:", fruitList.includes("橙子"));
      let bigNums = [5, 12, 8, 130, 44];
      let found = bigNums.find((num) => num > 10);
      console.log("find >10:", found);

      // 数组转换
      console.log("\n--- 数组转换 ---");
      let doubled = nums.map((num) => num * 2);
      console.log("map:", doubled);
      let filtered = nums.filter((num) => num > 2);
      console.log("filter >2:", filtered);
      let sum = nums.reduce((total, num) => total + num, 0);
      console.log("reduce sum:", sum);
      let str = nums.join("-");
      console.log("join:", str);

      // 排序和反转
      let unsorted = [3, 1, 4, 2];
      console.log("\n--- 排序和反转 ---");
      console.log("排序前:", unsorted);
      unsorted.sort();
      console.log("默认排序:", unsorted);
      unsorted.sort((a, b) => b - a);
      console.log("降序排序:", unsorted);
      unsorted.reverse();
      console.log("反转:", unsorted);

      // 其他实用方法
      console.log("\n--- 其他实用方法 ---");
      console.log("isArray:", Array.isArray([1, 2, 3]));
      let arr1 = [1, 2],
        arr2 = [3, 4];
      let combined = [...arr1, ...arr2];
      console.log("合并数组:", combined);
      let original = [1, 2, 3];
      let copy = [...original];
      console.log("复制数组:", copy);
    </script>
  </body>
</html>
